package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.PageResult;
import com.itheima.dto.Simple;
import com.itheima.dto.SubjectsDto;
import com.itheima.mapper.SubjectsMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Subjects;
import com.itheima.pojo.User;
import com.itheima.service.SubjectsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SubjectsServiceImpl implements SubjectsService {

    @Autowired
    private SubjectsMapper subjectsMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult subjectsPage(String subjectName, Integer page, Integer pagesize) {

        IPage<Subjects> p = new Page<>(page,pagesize);

        LambdaQueryWrapper<Subjects> wapper = new LambdaQueryWrapper<>();
        wapper.like(null != subjectName && "" !=subjectName, Subjects::getSubjectName,subjectName);
        IPage<Subjects> subjectsIPage = subjectsMapper.selectPage(p, wapper);
        List<Subjects> records = subjectsIPage.getRecords();
        String s = JSON.toJSONString(records);
        List<SubjectsDto> subjectsDtos = JSON.parseArray(s, SubjectsDto.class);
        subjectsDtos.stream().forEach(c->{
            User user = userMapper.selectById(c.getCreatorID());
            c.setUsername(user.getUsername());
        });
        PageResult pageResult = new PageResult((int)subjectsIPage.getTotal(), pagesize, (int) subjectsIPage.getPages(), page, subjectsDtos);
        return pageResult;
    }

    @Override
    public void modifySubjectsByid(Subjects subjects) {
         subjectsMapper.updateById(subjects);
    }

    @Override
    public void removeSubjectsByid(Integer id) {
        subjectsMapper.deleteById(id);
    }

    @Override
    public Integer addSubjects(Subjects subjects) {

        subjectsMapper.insert(subjects);
        return subjects.getId();
    }

    @Override
    public SubjectsDto findSubjectsById(Integer id) {
        SubjectsDto subjectsDto = (SubjectsDto) subjectsMapper.selectById(id);
        User user = userMapper.selectById(subjectsDto.getCreatorID());
        subjectsDto.setUsername(user.getUsername());
        return subjectsDto;
    }

    @Override
    public List<Simple> simple() {


        List<Simple> list = subjectsMapper.selectIdAndName();
        return list;
    }
}
